import React, { Component } from "react";
import { InputItem, Modal, Toast } from "antd-mobile";
import MainLayout from "../../../component/mainLayout/mainLayout";
import { createForm } from "rc-form";
import SendMSGCode from "../../../component/sendMSGCode/sendMSGCode";
import yhTools from "../../../tools/yh";
import { channelCode, InterfaceG } from "../../../config/Config";
import "./TransferXHBOut.scss";

class TransferXHBOut extends Component {
	constructor(props) {
		super(props);

		this.state = {
			loadStatus: "1", //'0'：数据加载中，'1'：加载完成，'2'：加载失败
			productName: "小辉宝", //产品名称
			channelCode: "YHB", //渠道号
			productId: "", //产品ID
			tradeNumber: "", //订单编号
			msgSubmitButtText: "确定",
			msgSubmitButtStatus: "3",
			productRedeemInitData: {}, //产品初始接口返回数据
			inputValue: "",
			remainingMoney: 0, //留存金额
			distributeProfitAmt: "", //已派发利息
			profitAmt: "", //利息金额
			totalAmt: "", //到账金额,
			tipMessage: "", //提示信息
			buyBtnClass: "btn redeem-btn btn-disable", //支取按钮
			drawAbleClass: "redeem-all redeem-able", //全部支取按钮
			editable: true, //是否可编辑
			productFCode: "", //产品code
			isB: false, // 是否是B产品

			showMsgBox: false, //控制是否显示发送验证码弹窗
			messageSerialNumber: "", //发送短信成功后返回的流水号
			sendSuccessPhone: "", //发送短信成功后返回的手机号
			modal1: false
		};
		this.debounceCalB = yhTools.delayDebounce(this.calB, 800); //根据使用反馈，适当调整延时时间
		// this.calB = debounce(this.calB, 1000);//调用设定好的防抖方法。最后一次输入后1000ms必须请求网络测算
	}

	componentDidMount() {
		this.prepareData();
		// this.fakeData();
	}

	fakeData = () => {
		this.setState({
			productRedeemInitData: {
				unadvanceAmt: 200,
				buyDate: "2019-10-20",
				advanceRate: "0.90",
				holdDays: 90
			}
		});
	};

	prepareData = () => {
		const { tradeNumber } = this.props.match.params;
		const { channelCode } = this.state;
		this.setState({ tradeNumber });
		let objs = {
			url: InterfaceG.financeRedeemInit,
			params: {
				channelCode,
				tradeNumber
			},
			_alertShow: false
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				let productRedeemInitData = res.data;
				this.setState({
					productRedeemInitData,
					isB: productRedeemInitData.productDetail === "B"
				});
			} else {
				Toast.info(res.message, 2);
				this.setState({
					loadStatus: "2"
				});
			}
		});
	};
	// B产品调用试算接口
	calB = () => {
		const { tradeNumber } = this.props.match.params;
		const { channelCode, inputValue: redeemAmt } = this.state;
		let objs = {
			url: InterfaceG.financeTrial,
			params: {
				channelCode,
				tradeNumber,
				redeemAmt
			},
			_alertShow: false
		};
		yhTools.request(objs).then(res => {
			if (res.code === "0") {
				const data = res.data;
				this.setState({
					buyBtnClass: "btn redeem-btn btn-able",
					totalAmt: data.totalAmt, // 到账金额
					profitAmt: data.currentProfitAmt, //利息金额
					distributeProfitAmt: data.distributeProfitAmt //派发利息
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	};
	//支取
	redeemClick() {
		if (this.refs.redeemProduct.className.split(" ")[2] != "btn-able") {
			return;
		}
		let _that = this;
		this.timer1 && clearTimeout(this.timer1);
		this.timer1 = setTimeout(() => {
			_that.sendYzm();
		}, 300);
	}
	//填充全部金额
	allRedeemAction = () => {
		// if (this.state.productRedeemInitData.productFCode == "FYCPL") return;
		if (
			!this.state.productRedeemInitData &&
			!this.state.productRedeemInitData.unadvanceAmt
		)
			return;
		this.setState(
			{
				inputValue: this.state.productRedeemInitData.unadvanceAmt
			},
			function () {
				this.checkValue(this.state.inputValue);
			}
		);
	};
	//A获取利息
	getProfitAmt = flag => {
		//输入数据不满足规则时，将动态算出的利息和到账金额全部清零
		if (!flag) {
			this.setState({
				profitAmt: "0.00",
				totalAmt: "0.00"
			});
			return;
		}

		const { inputValue, productRedeemInitData } = this.state;

		//提前支取试算收益=支取本金*0.4%*实际持有天数（算头不算尾）/360
		let profitAmt = (
			(((parseFloat(inputValue) *
				parseFloat(productRedeemInitData.advanceRate)) /
				100) *
				parseFloat(productRedeemInitData.holdDays)) /
			360
		).toFixed(2); //向上取整
		console.log(
			150,
			inputValue,
			parseFloat(inputValue),
			parseFloat(productRedeemInitData.advanceRate),
			parseFloat(productRedeemInitData.holdDays)
		);
		console.log(170, profitAmt);
		// let profitAmt = Math.floor(parseFloat(this.state.inputValue)*parseFloat(this.state.productRedeemInitData.advanceRate)/100*parseFloat(this.state.productRedeemInitData.holdDays)/360*100)/100; //向下取整
		let totalAmt = (parseFloat(inputValue) + parseFloat(profitAmt)).toFixed(2);

		this.setState({
			profitAmt,
			totalAmt
		});
	};
	resetBValue = () => {
		this.setState({
			totalAmt: "", // 到账金额
			profitAmt: "", //利息金额
			distributeProfitAmt: ""
		});
	};

	//校验输入框
	checkValue = value => {
		const isB = this.state.isB;
		let inputValue = value;
		let preValue = this.state.inputValue;
		if (value && !/^(([1-9]\d*)|0)(\.\d{0,2}?)?$/.test(value)) {
			if (value === ".") {
				inputValue = "0.";
			} else {
				inputValue = preValue;
			}
		}
		// 没有值的时候，b产品利息等要复位
		isB && !inputValue && this.resetBValue();
		let tipMessage = ""; //提示信息
		let buyBtnClass = "btn redeem-btn btn-disable"; //购买按钮
		let drawAbleClass = "redeem-all redeem-able"; //支取按钮
		let { productRedeemInitData } = this.state;
		let flag = false;

		if (inputValue == "") {
			flag = false;
			tipMessage = "";
		} else if (
			inputValue.toString().substr(inputValue.toString().length - 1, 1) === "."
		) {
			tipMessage = <div style={{ color: "red" }}>请输入正确金额</div>;
		} else {
			// if (productRedeemInitData.unadvanceAmt != Number(inputValue)) {
			//     drawAbleClass = "redeem-all redeem-able";
			// } else {
			//     drawAbleClass = "redeem-all redeem-disable";
			// }
			// if (Number(inputValue) < Number(productRedeemInitData.remainingMoney)) {
			//     tipMessage = (
			//         <div style={{ color: "red" }}>支取金额{productRedeemInitData.remainingMoney}元起</div>
			//     );
			//     flag = false;
			// }
			// 如果不是全部支取 && 留存金额低于50
			if (
				productRedeemInitData.unadvanceAmt - Number(inputValue) <
					Number(productRedeemInitData.remainingMoney) &&
				productRedeemInitData.unadvanceAmt - Number(inputValue) != 0
			) {
				if (
					Number(productRedeemInitData.unadvanceAmt) - Number(inputValue) <
					0
				) {
					tipMessage = (
						<div style={{ color: "red" }}>
							最大可支取的金额为
							{productRedeemInitData.unadvanceAmt}元
						</div>
					);
					flag = false;
				} else {
					tipMessage = (
						<div style={{ color: "red" }}>
							单笔存单留存金额不得少于{productRedeemInitData.remainingMoney}元
						</div>
					);
					flag = false;
				}
			}
			// 如果输入金额大于50，且留存金额大于50 || 全部取出
			if (
				(Number(inputValue) > 0 &&
					productRedeemInitData.unadvanceAmt - Number(inputValue) >=
						Number(productRedeemInitData.remainingMoney)) ||
				productRedeemInitData.unadvanceAmt - Number(inputValue) == 0
			) {
				if (!isB) {
					//B产品在试算出结果之后再显示
					buyBtnClass = "btn redeem-btn btn-able";
				}

				flag = true;
			}
		}

		this.setState(
			{
				tipMessage,
				buyBtnClass,
				drawAbleClass,
				inputValue
			},
			() => {
				isB && flag && this.debounceCalB();
				!isB && this.getProfitAmt(flag);
			}
		);
	};
	formatValue = distributeProfitAmt => {
		if (!distributeProfitAmt) {
			//初始值
			return "未计算";
		} else if (!Number(distributeProfitAmt)) {
			//请求接口，返回0.00
			return distributeProfitAmt;
		} else {
			// 大于0，要加负号
			return -distributeProfitAmt;
		}
	};
	render() {
		const _pageParams = {
			header: {
				title: "转出小辉宝"
			},
			history: this.props.history,
			loadStatus: this.state.loadStatus,
			cacheLifecycles: this.props.cacheLifecycles
		};
		let {
			productRedeemInitData,
			profitAmt,
			totalAmt,
			tipMessage,
			buyBtnClass,
			drawAbleClass,
			inputValue,
			isB,
			distributeProfitAmt,
			sendSuccessPhone = "",
			showMsgBox
		} = this.state;
		return (
			<MainLayout pageParams={_pageParams}>
				<div className="transfer-XHB-out">
					<div className="money">
						<div className="bank_logo"></div>
						<div className="con">
							<div className="title">
								小辉宝{" "}
								<span className="font-grey">
									({productRedeemInitData.buyDate}转入){" "}
								</span>
							</div>
							<div className="content">
								持有金额：{productRedeemInitData.unadvanceAmt}元 可用金额：
								{productRedeemInitData.unadvanceAmt}元
							</div>
						</div>
					</div>
					<div className="line"></div>
					<div className="bank_inp flexCenter">
						<div className="title">转出金额</div>
						<div className="bank_inp_con">
							<div className="flexLeft b_left">
								<InputItem
									type="money"
									placeholder="请输入转出金额"
									onChange={this.checkValue}
									editable={this.state.editable}
									value={this.state.inputValue}
									clear
									moneyKeyboardAlign="left"
									extra={
										<div
											onClick={() => this.allRedeemAction()}
											className={drawAbleClass}
										>
											全部转出
										</div>
									}
								>
									¥
								</InputItem>
							</div>
						</div>
					</div>
					<div className="tipMessage">{tipMessage}</div>

					{!!inputValue && !isB ? (
						<div className="p_list pagePading font28">
							<div className="p_cell flexBetween">
								<div className="colorBlack">预计到账金额：</div>
								<div className="colorLight">¥{totalAmt}</div>
							</div>
							<div className="p_cell flexBetween">
								<div className="colorBlack">预计利息金额：</div>
								<div className="colorLight">¥{profitAmt}</div>
							</div>
						</div>
					) : (
						<div className="p_list pagePading font28 font-grey">
							部分支取时，留存金额不低于{productRedeemInitData.remainingMoney}元
						</div>
					)}

					{!isB ? (
						<div className="bottom-tips">
							<span
								dangerouslySetInnerHTML={{
									__html: productRedeemInitData.profitRule
								}}
							></span>
						</div>
					) : (
						<div className="bottom-tips b-list">
							<span>
								计息规则：
								<div
									className="right-look-ex"
									onClick={this.openIntroduce.bind(this)}
								>
									查看例子
								</div>
								<br />
								提前转出活期计息(0.40%)，已派发利息需扣回
							</span>
							<ul>
								<li>
									<span>预计活期利息(元)</span>
									<span>{profitAmt || "未计算"}</span>
								</li>
								<li>
									<span>提前转出扣回已派利息(元)</span>
									<span>{this.formatValue(distributeProfitAmt)}</span>
								</li>
								<li>
									<span>预计到账金额(元)</span>
									<span>{totalAmt || "未计算"}</span>
								</li>
							</ul>
						</div>
					)}
					<div className="p_butt">
						<div
							className={buyBtnClass}
							ref="redeemProduct"
							onClick={() => this.redeemClick()}
						>
							确认转出
						</div>
					</div>
					<Modal
						popup
						className="transfer-xhb-out-modal"
						visible={this.state.modal1}
						onClose={() => {}}
						animationType="slide-up"
					>
						<div className="div-far">
							<div className="line-1">
								<div className="title">举例说明</div>
								<img
									className="close-img"
									src={require("../../../images/icon-open-account-close.png")}
									onClick={this.onCloseM()}
								/>
							</div>
							<div className="line-2">
								12月1日购买小辉宝10000元，2月25日部分支取3000元。
								<br />
								①提前支取活期本息和=3000+3000*86（持有天数）*0.4%（活期利率）/360
								<br />
								②部分提前支取前的已付利息=10000*4.8%/12（周期派息金额）*2(派息周期)
								<br />
								③部分提前支取后的剩余本金已付利息=7000*4.8%/12（周期派息金额）*2(派息周期)
								<br />
								提前支取时到账金额=①-（②-③）=3002.87-（80-56）=2978.87元
							</div>
						</div>
					</Modal>
				</div>
				<SendMSGCode
					ref={ref => {
						this.sendCode = ref;
					}}
					getYZMCode={this.sendYzm.bind(this)}
					sendSuccessPhone={sendSuccessPhone}
					submitCode={this.submitCode.bind(this)}
					closeSendModal={this.closeSendModal.bind(this)}
					showMsgBox={showMsgBox}
					seconds={60}
				/>
			</MainLayout>
		);
	}

	//短信验证码验证接口
	sendYzm() {
		const _this = this;
		let objs = {
			url: InterfaceG.smsMessage,
			params: {
				channelCode: channelCode
			},
			_alertShow: false
		};
		Toast.loading("加载中...", 15);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code == "0") {
				_this.sendCode.countdown();
				_this.setState({
					sendSuccessPhone: res.data.sendSuccessPhone,
					messageSerialNumber: res.data.messageSerialNumber,
					showMsgBox: true //显示验证码
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	//提交回调
	submitCode(activeCode) {
		let _that = this;
		const { channelCode, inputValue, tradeNumber } = this.state;
		let objs = {
			url: InterfaceG.financeRedeem,
			params: {
				channelCode,
				redeemAmount: inputValue,
				tradeNumber,
				activeCode,
				messageSerialNumber: this.state.messageSerialNumber //短信流水号
			},
			_alertShow: false
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				_that.setState({
					showMsgBox: false
				});
				setTimeout(function () {
					_that.props.history.push({
						pathname: `/transferXHBSuccess/out/${JSON.stringify(res.data)}`
					});
				}, 100);
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	//关闭验证码弹框
	closeSendModal() {
		this.setState({
			showMsgBox: false
		});
	}
	//打开大额介绍
	openIntroduce() {
		this.setState({ modal1: true });
	}
	onCloseM = () => () => {
		this.setState({
			modal1: false
		});
	};
}

const TransferXHBOutPage = createForm()(TransferXHBOut);
export default TransferXHBOutPage;
